// packageFT/seek-guide/seek-guide.js
const app = getApp()
const delayTime = 2 * 24 * 60 * 60 * 1000
import { formatDate } from '../../utils/util'
import WxValidate from '../../utils/WxValidate'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      travelCityValue: '',
      province_id: '',
      province_name: '',
      city_name: '',
      city_id: '',
      start_at: '',
      finish_at: '',
      travelTimeValue: '',
      travelDays: 0,
      person_num: 1,
      attractionsText: [],
      scenic_spots_ids: [],
      travel_tool: '',
      guideLevelText: '',
      guide_level_id: '',
      appointGuideValue: '',
      guide_id: '',
      realname: '',
      mobile: '',
      remark: '',
      know: 0
    },
    chooseTravelCityShow: false,
    travelCityOptions: [],
    travelTimeShow: false,
    minDate: new Date().getTime() + delayTime,
    attractionsList: [],
    noAttractionsTip: '请先选择【出行城市】', 
    chooseTravelCarShow: false,
    travelCarValue: '',
    travelCarColumns: [{value: 1, text: '五座车'}, {value: 2, text: '七座车'}, {value: 3, text: '自备车'}],
    chooseGuideLevelShow: false,
    guideLevelColumns: [],
    guideLevels: {},
    guideLevelPrice: 0,
    appointGuideShow: false,
    guideList: [],
    btnLoading: false,
    defaultPriceRatio: ''
  },

  /**
   * 显示/隐藏弹窗
   * @param {Object} e 
   */
  popupToggle: function(e) {
    const { text, show } = e.currentTarget.dataset
    this.setData({
      [text]: show
    })
  },

  /**
   * 指定导游显示导游列表
   * 前提条件是已经选择了出行城市和导游级别
   */
  showGuideList: function() {
    const { travelCityValue, guide_level_id } = this.data.formData
    if (app._isTextEmpty(travelCityValue)) {
      app.tips('请先选择【出行城市】')
      return
    }
    if (app._isTextEmpty(guide_level_id)) {
      app.tips('请先选择【导游级别】')
      return
    }
    this.setData({ guideList: [] })
    this.getGuideList()
  },

  /**
   * 获取导游列表
   */
  getGuideList: function() {
    const { city_id, guide_level_id } = this.data.formData
    const urlStr = app.getNetAddresss('plugin.guide.frontend.index.guide-lists')
    const data = {
      region_city_id: city_id,
      level_id: guide_level_id
    }
    const _this = this
    wx.showLoading({
      title: '数据获取中...',
    })
    app._postNetWork({
      url: urlStr,
      data,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          if (resData.data && resData.data.length) {
            _this.setData({ 
              // 导游列表数据
              guideList: resData.data,
              // 显示选择导游列表
              appointGuideShow: true
            })
          } else {
            app.tips('暂无符合条件的导游！')
          }
        } else {
          app.tips(resData.msg || '数据获取失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 出行城市选择结束
   * @param {Object} e 
   */
  chooseTravelCityFinish: function(e) {
    const { selectedOptions, value } = e.detail;
    const fieldValue = selectedOptions[1].text
    this.setData({
      'formData.travelCityValue': fieldValue,
      'formData.province_id': selectedOptions[0].value,
      'formData.province_name': selectedOptions[0].text,
      'formData.city_id': value,
      'formData.city_name': selectedOptions[1].text,
      chooseTravelCityShow: false
    })
    this.getAttractionsList(value)
  },

  /**
   * 根据出行城市id获取景点列表
   * @param {String | Number} city_id 出行城市id
   */
  getAttractionsList: function(city_id) {
    // 清除已选中的景点
    this.setData({
      attractionsText: [],
      scenic_spots_ids: []
    })
    const _this = this
    const urlStr = app.getNetAddresss('scenicSpots.list.index')
    const data = { city_id }
    app._postNetWork({
      url: urlStr,
      data,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.setData({ attractionsList: resData.data})
          // if (!resData.data.length) {
          //   _this.setData({
          //     noAttractionsTip: `暂无【${_this.data.formData.city_name}】的景点，请选择其他出行城市！`
          //   })
          // }
        } else {
          app.tips(resData.msg || '获取景点数据失败！')
        }
      }
    })
  },

  /**
   * 出行时间选择确认
   * @param {Object} e 
   */
  travelTimeConfirm: function(e) {
    const start = e.detail[0]
    const end = e.detail[1]
    const startStr = formatDate(start)
    const endStr = formatDate(end)
    const day = (end - start)/1000/60/60/24 + 1
    const travelTimeValue = `${startStr}~${endStr}(${day}天)`
    const start_at = Math.floor(new Date(startStr.replace(/-/g, '/')).getTime()) / 1000
    // 结束时间为23:59:59，结束时间戳要加上的毫秒数
    const endDiff = (23 * 60 * 60 + 59 * 60 + 59) * 1000
    const finish_at = Math.floor(new Date(endStr.replace(/-/g, '/')).getTime() + endDiff) / 1000
    this.setData({
      'formData.travelDays': day,
      'formData.travelTimeValue': travelTimeValue,
      'formData.start_at': start_at,
      'formData.finish_at': finish_at,
      travelTimeShow: false
    })
  },

  /**
   * 数据双向绑定
   * @param {Object} e 
   */
  updateFormData: function(e) {
    const { formdatakey } = e.currentTarget.dataset
    const value = e.detail
    const key = 'formData.' + [formdatakey]
    this.setData({
      [key]: value 
    })
  },

  /**
   * 景点点击
   * @param {Object} e 
   */
  attractionsClick: function(e) {
    const { id, name } = e.currentTarget.dataset.item
    let ids = this.data.formData.scenic_spots_ids
    let texts = this.data.formData.attractionsText
    const idIndex = ids.findIndex(item => item == id)
    const textIndex = texts.findIndex(item => item == name)
    // 存在id
    if (idIndex > -1) {
      ids.splice(idIndex, 1)
    } else {
      ids.push(id)
    }
    // 存在文字
    if (textIndex > -1) {
      texts.splice(textIndex, 1)
    } else {
      texts.push(name)
    }
    this.setData({
      'formData.scenic_spots_ids': ids,
      'formData.attractionsText': texts
    })
  },

  /**
   * 出行工具选择确认
   * @param {Object}} e 
   */
  travelCarConfirm: function(e) {
    const { value } = e.detail
    this.setData({
      travelCarValue: value.text,
      'formData.travel_tool': value.value,
      chooseTravelCarShow: false
    })
  },

  /**
   * 导游级别选择确认
   * @param {Object}} e 
   */
  guideLevelConfirm: function(e) {
    const { text, price, id } = e.detail.value
    this.setData({
      'formData.guideLevelText': text,
      'formData.guide_level_id': id,
      guideLevelPrice: price,
      chooseGuideLevelShow: false
    })
  },

  /**
   * 导游选择确认
   */
  guideConfirm: function() {
    const component = this.selectComponent("#guide-list")
    const { guideID, guideName }= component.data
    // if (!guideID) {
    //   app.tips('请选择导游')
    //   return
    // }
    this.setData({
      'formData.guide_id': guideID,
      'formData.appointGuideValue': guideName,
      appointGuideShow: false
    })
  },

  /**
   * 选中知晓
   * @param {Object} e 
   */
  knowChange: function(e) {
    this.setData({
      'formData.know': this.data.formData.know ? 0 : e.detail
    })
  },

  /**
   * 取消寻找导游
   */
  goBack: function() {
    wx.navigateBack({delta: -1})
  },

  /**
   * 发布需求
   */
  submitForm: function() {
    // 验证表单
    if (!this.WxValidate.checkForm(this.data.formData)) {
      const error = this.WxValidate.errorList[0]
      app.tips(error.msg)
      return
    }
    const { guideLevelPrice, formData } = this.data
    const {
      province_id,
      province_name,
      city_name,
      city_id,
      start_at,
      finish_at,
      person_num,
      scenic_spots_ids,
      travel_tool,
      guide_level_id,
      guide_id,
      realname,
      mobile,
      remark,
      travelDays
    } = formData
    const data = {
      province_id,
      province_name,
      city_name,
      city_id,
      start_at,
      finish_at,
      person_num,
      scenic_spots_ids: scenic_spots_ids.join(','),
      travel_tool,
      guide_level_id,
      guide_id,
      realname,
      mobile,
      remark,
      service_fee: travelDays * guideLevelPrice
    }
    const urlStr = app.getNetAddresss('plugin.guide.frontend.create-need.publish')
    const _this = this
    this.setData({ btnLoading: true })
    wx.showLoading({
      title: '数据提交中...',
    })
    app._postNetWork({
      url: urlStr,
      data,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          wx.showModal({
            title: '成功',
            content: '需求发布成功，等待导游接单！',
            showCancel: false,
            complete: (resC) => {
              if (resC.confirm) {
                const { tmplIds } = app.data
                wx.requestSubscribeMessage({
                  tmplIds: tmplIds[0],
                  complete: function() {
                    wx.navigateBack({ delta: -1 })
                  }
                })
              }
            }
          })
        } else {
          app.tips(resData.info || '需求发布失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
        _this.setData({ btnLoading: false })
      }
    })
    // app.tips('发布需求，待完善...')
  },

  /**
   * 获取省市列表(出行城市)
   */
  getAddress: function() {
    wx.showLoading({
      title: '加载中...',
    })
    const _this = this
    let urlStr = app.getNetAddresss("member.member-address.address");
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const province = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              return {
                text: item1.areaname,
                value: item1.id + ''
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          _this.setData({ travelCityOptions: province})
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 表单验证
   */
  initValidate: function() {
    const rules = {
      travelCityValue: {
        required: true
      },
      travelTimeValue: {
        required: true
      },
      // scenic_spots_ids: {
      //   isEmptyArray: true
      // },
      travel_tool: {
        required: true
      },
      guide_level_id: {
        required: true
      },
      realname: {
        required: true
      },
      mobile: {
        required: true,
        tel: true
      },
      know: {
        min: 1
      }
    }
    const message = {
      travelCityValue: {
        required: '请选择出行城市'
      },
      travelTimeValue: {
        required: '请选择出行时间'
      },
      // scenic_spots_ids: {
      //   isEmptyArray: '请选择景点'
      // },
      travel_tool: {
        required: '请选择出行工具'
      },
      guide_level_id: {
        required: '请选择导游级别'
      },
      realname: {
        required: '请输入联系人'
      },
      mobile: {
        required: '请输入联系电话',
        tel: '请输入正确的手机号码'
      },
      know: {
        min: '必须勾选我已知晓才能提交需求'
      }
    }
    this.WxValidate = new WxValidate(rules, message)
    this.WxValidate.addMethod('isEmptyArray', (value, param) => {
      return value.length > 0
    })
  },

  /**
   * 获取导游级别列表
   */
  getGuideLevel: function() {
    const urlStr = app.getNetAddresss('plugin.guide.frontend.level.lists')
    const _this = this
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.setData({ defaultPriceRatio: resData.data.set.default_price_ratio})
          if (resData.data.levels && resData.data.levels.length) {
            let levels = {}
            const list = resData.data.levels.map(item => {
              levels[item.id] = item.name
              return {
                id: item.id,
                text: `${item.name}(${item.price}/天)`,
                price: item.price
              }
            })
            _this.setData({ guideLevelColumns: list, guideLevels: levels })
          }
        } else {
          app.tips(resData.msg || '请求错误！')
        }
      }
    })
  },

  /**
   * 获取会员信息，自动填写联系人和联系电话
   */
  getMemberInfo: function() {
    const urlStr = app.getNetAddresss("member.member.member-data")
    const _this = this
    wx.showLoading({ title: '加载中...' })
    app._getNetWork({
      url: urlStr,
      data: {
        v: 2,
        basic_info:1
      },
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const { member } = resData.data
          _this.setData({
            'formData.realname': member.realname || member.username || member.nickname || '',
            'formData.mobile': member.mobile || ''
          })
        } else {
          app.tips(resData.msg || '会员数据加载失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getAddress()
    this.initValidate()
    this.getGuideLevel()
    this.getMemberInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})